package com.wx.forum.service.impl;

import com.wx.forum.service.IAuthService;
import com.wx.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AuthServicelmpl implements IAuthService {
    @Autowired
    private StringRedisTemplate redisTemplateString;
    @Autowired
    private RedisTemplate redisTemplate;


    private static final String REDIS_TOKEN = "user_token:";

    private static final long TOKEN_TIME = 15;
    /**
     * 保存token到redis
     * @param userId
     * @param token
     */
    @Override
    public void saveToken(Long userId, String token) {
        redisTemplateString.opsForValue().set(REDIS_TOKEN + userId,token,TOKEN_TIME, TimeUnit.DAYS);
        log.info(REDIS_TOKEN + userId);
    }
    /**
     * 从redis获取token
     * @param userId
     * @return
     */
    @Override
    public String getToken(Long userId) {
       return redisTemplateString.opsForValue().get(REDIS_TOKEN + userId);
    }
    /**
     * 删除token
     * @param userId
     */
    @Override
    public void deleteToken(Long userId) {
        redisTemplateString.delete((REDIS_TOKEN + userId));
    }

    /**
     * 处理点赞关系
     * @param thumbsKey
     *
     */
    public void thumbsOnlyOne(String thumbsKey){
        //1表示该用户以及点赞该帖子，0表示未点赞
        redisTemplate.opsForValue().set(thumbsKey,"1");
    }

    /**
     * 取消点赞
     * @param thumbsKey
     */
    public void cancelThumbs(String thumbsKey){
        //1表示该用户以及点赞该帖子，0表示未点赞
        redisTemplate.opsForValue().set(thumbsKey,"0");
    }

    /**
     * 判断是否重复点赞
     * @param userid
     * @param articleId
     * @return
     */

    @Override
    public Boolean repeThumbs(Long userid, Long articleId) {
        String thumbsKey = userid + "::" + articleId;
//        //如果用户第一次点赞就生成点赞关系
        if(redisTemplate.hasKey(thumbsKey) == false){
            cancelThumbs(thumbsKey);
        }
        String thumbsValue = (String) redisTemplate.opsForValue().get(thumbsKey);
        if(!StringUtil.isEmpty(thumbsKey) && "1".equals(thumbsValue)){
            return true;
        }else {
            return false;
        }
    }

}
